package net.oschina.git.hikoyan.helloapi.filter;


import net.oschina.git.hikoyan.helloapi.async.flowcontrol.FlowControlResult;
import net.oschina.git.hikoyan.helloapi.async.flowcontrol.QPSFlowControl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求头参数校验
 *
 * @author lry
 */
public class GatewayFilter extends OncePerRequestFilter {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private QPSFlowControl flowControl = new QPSFlowControl();

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        //模拟星星打车进来
        FlowControlResult fcresult = flowControl.doQPSFlowControl("xingxingdache");
        if (fcresult == FlowControlResult.FC_OK) {
            filterChain.doFilter(request, response);
        } else {
            if (fcresult == FlowControlResult.CCT_OVERFLOW) {
                logger.error("并发流量溢出");
                response.getOutputStream().write("并发流量溢出".getBytes("UTF-8"));
            } else if (fcresult == FlowControlResult.QPS_OVERFLOW) {
                logger.error("QPS流控溢出");
                response.getOutputStream().write("QPS流控溢出".getBytes("UTF-8"));
            } else if (fcresult == FlowControlResult.CCT_EXCEPTION) {
                logger.error("并发异常");
                response.getOutputStream().write("并发异常".getBytes("UTF-8"));
            } else if (fcresult == FlowControlResult.QPS_EXCEPTION) {
                logger.error("QPS异常");
                response.getOutputStream().write("QPS异常".getBytes("UTF-8"));
            }
            return;
        }
    }
}
